package cn.bby.query.server.application.manager.impl;

import cn.bby.query.base.constant.AdvQueryErrorCode;
import cn.bby.query.base.constant.AdvSettingKey;
import cn.bby.query.base.exception.AdvQueryException;
import cn.bby.query.base.model.req.DoQueryReq;
import cn.bby.query.base.model.req.QueryRequest;
import cn.bby.query.base.model.req.QueryResponse;
import cn.bby.query.server.application.manager.DataQueryManager;
import cn.bby.query.server.application.manager.SystemStatusManager;
import cn.bby.query.server.domain.agg.metadata.entity.InterfaceInfo;
import cn.bby.query.server.domain.agg.metadata.repository.InterfaceInfoRepository;
import cn.bby.query.server.domain.service.manager.DataStorageManager;
import cn.bby.query.server.domain.share.constant.InterfaceStatus;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ben
 * @since 2025/4/23 23:38
 */
@Service
public class DataQueryManagerImpl implements DataQueryManager {
    @Resource
    private InterfaceInfoRepository interfaceInfoRepository;
    @Resource
    private DataStorageManager dataStorageManager;
    @Resource
    private SystemStatusManager systemStatusManager;

    @Override
    public QueryResponse<JSONObject> doQuery(DoQueryReq req) {
        if (!systemStatusManager.isHealth()) {
            throw new AdvQueryException(AdvQueryErrorCode.NO_INTERFACE, req.getRequest());
        }
        // 默认条件
        initDefaultQueryCondition(req);
        // 获取请求地址
        InterfaceInfo interfaceDTO = CollUtil.getFirst(interfaceInfoRepository.getByInterfaceNames(req.getServiceName(), List.of(req.getInterfaceName())));
        if (interfaceDTO == null || !InterfaceStatus.READY.equals(interfaceDTO.getStatus())) {
            throw new AdvQueryException(AdvQueryErrorCode.NO_INTERFACE, req.getRequest());
        }
        return dataStorageManager.query(interfaceDTO, req.getRequest());
    }

    private void initDefaultQueryCondition(DoQueryReq req) {
        QueryRequest request = req.getRequest();
        if (request == null) {
            request = new QueryRequest();
            request.setPage(1);
            request.setSize(AdvSettingKey.getInteger(AdvSettingKey.DEFAULT_PAGE_SIZE));
            req.setRequest(request);
        }
    }
}
